﻿using Microsoft.SharePoint.Client;
using StockDashboardWeb;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AG_Apps_Cloud_Services_WCF_Web_Role.Apps
{
    public partial class Dashboard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                String connectionString = "";
                try
                {

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    clientContext.Load(clientContext.Web, web => web.CurrentUser);
                    clientContext.ExecuteQuery();

                    //connectionString = spContext.GetDatabaseConnectionString();
                    connectionString =AppInstance.RetrieveAppDatabaseConnectionString(clientContext).Value;

                    if (connectionString == null)
                    {
                        connectionString = ConfigurationManager.ConnectionStrings["StockDashboardContext"].ConnectionString;
                    }
                }

                    string script = @"

$(document).ready(function () {

    stockDashboard = new ArthurGraus.StockDashboard();
    stockDashboard.hostWebUrl = decodeURIComponent(getQuerystring('SPHostUrl'));
    stockDashboard.appWebUrl = decodeURIComponent(getQuerystring('SPAppWebUrl'));
    stockDashboard.connectionString = '{ConnectionString}'
    var scriptbase = stockDashboard.hostWebUrl + '/_layouts/15/';

    $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
                function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', stockDashboard.initialize); }
                );
        }
        );
	

	ko.applyBindings(stockDashboard);
});

".Replace("{ConnectionString}" ,connectionString);


                    ScriptManager.RegisterStartupScript(this, this.GetType(),"startup", script, true);

                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}